package com.qiujianwei.study.authcenter.auth;

import com.qiujianwei.study.authcenter.entity.LoginUser;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CustomReactiveAuthenticationManager implements ReactiveAuthenticationManager {

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> powers = loginUser.getPowers();
        List<SimpleGrantedAuthority> authorities = null;
        if (CollectionUtils.isEmpty(powers)){
            authorities = new ArrayList<>();
        }else{
            authorities = powers.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), null, authorities);
        return Mono.just(usernamePasswordAuthenticationToken);
    }

}
